#include "graphics.h"
#include "snake.h"
#include "point.h"
#include <stdio.h>
#include <string.h>

void gotoxy(int x, int y)
{
	char essq[100], xstr[100], ystr[100];

	sprintf(xstr, "%d", x);
	sprintf(ystr, "%d", y);
	essq[0] = '\0';

	strcat(essq, "\033[");
	strcat(essq, ystr);
	strcat(essq, "d");

	strcat(essq, "\033[");
	strcat(essq, xstr);
	strcat(essq, "G");

	printf("%s", essq);
}

void gotoPoint(Point point)
{
	gotoxy(point.x, point.y);
}

void drawBorder()
{
	int i;
	char screenbuf[81];

	// 1. Print top header line
	screenbuf[0] = '+';
	for (i = 1; i <= 78; i++)
		screenbuf[i] = '-';
	screenbuf[79] = '+';
	screenbuf[80] = '\0';

	gotoxy(1, 1);
	printf("%s", screenbuf);

	// 2. Print lines of screen
	screenbuf[0] = '|';
	for (i = 1; i <= 78; i++)
		screenbuf[i] = ' ';
	screenbuf[79] = '|';

	for (i=1; i <= 20; i++)
	{
		gotoxy(1, 1 + i);
		printf("%s", screenbuf);
	}

	// 3. Print final header line
	screenbuf[0] = '+';
	for (i = 1; i <= 78; i++)
		screenbuf[i] = '-';
	screenbuf[79] = '+';
	screenbuf[80] = '\0';

	gotoxy(1, 22);
	printf("%s", screenbuf);
}

void drawSnake(Snake *ptrSnake)
{
	SnakePiece *thru = ptrSnake->ptrHead;

	while (thru != NULL)
	{
		gotoPoint(thru->point);
		printf("%c", ptrSnake->cSnakeChar);
		thru = thru->ptrNext;
	}

	fflush(stdout);
}

void drawFood()
{
	gotoPoint(objFoodPoint);
	printf("*");
	fflush(stdout);
}
